﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

using YmatouSeller.Notice.ApplicationService.Interface;
using YmatouSeller.Notice.Domain.Interface;
using YmatouSeller.NoticeAPI.Model.Entity;
using YmatouSeller.NoticeAPI.Model.Response;
using YmatouSeller.NoticeAPI.Model.Request;
using Ymatou.CommonService;
using Ymatou.User.Dto;
using Ymatou.User.ServerResponse;
using YmatouSeller.AccountAPI.Model.Request.SellerQueryRequest;
using YmatouSeller.AccountAPI.Model.Response.SellerQueryResponse;
using YmatouSeller.Notice.Common;
using YmatouSeller.NoticeAPI.Model.Enums;


namespace YmatouSeller.Notice.ApplicationService.Implement
{
    public class SystemNoticeManageService : ISystemNoticeManageService
    {
        [Dependency]
        public ISystemNoticeService systemNoticeService { get; set; }

        #region 消息通知管理

        /// <summary>
        /// 获取国家信息
        /// </summary>
        /// <returns></returns>
        public List<CountryInfo> GetAllCountry(string continent, int countryID, int selectType)
        {
            return systemNoticeService.GetAllCountry(continent, countryID, selectType);
        }

        /// <summary>
        /// 根据用户名获取用户ID
        /// </summary>
        /// <param name="loginIds"></param>
        /// <returns></returns>
        public List<UserInfo> GetUserIDLstByLoginIds(List<string> loginIds, int accoutType)
        {
            if (loginIds == null || loginIds.Count <= 0)
            {
                return null;
            }
            List<UserInfo> list = new List<UserInfo>();
            try
            {
                list = GetUserInfo(loginIds, accoutType);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private List<UserInfo> GetUserInfo(List<string> sloginList, int accoutType)
        {
            List<UserInfo> lst=new List<UserInfo>();
            if (sloginList == null)
                return lst;
            if (accoutType == 0)
            {
                var pageCount = sloginList.Count / 100 + (sloginList.Count % 100 > 0 ? 1 : 0);
                for (var i = 0; i < pageCount; i++)
                {
                    var _mails = sloginList.Skip(i * 100).Take(100).ToList();
                    List<string> strlst = new List<string>();
                    _mails.ForEach(x =>
                    {
                        strlst.Add(x);
                    });

                    lst.AddRange(GetUserInfo(null, strlst.ToArray(), 0));
                }
            }
            else
            {
                var pageCount = sloginList.Count/100 + (sloginList.Count%100 > 0 ? 1 : 0);
                for (var i = 0; i < pageCount; i++)
                {
                    var _mails = sloginList.Skip(i*100).Take(100).ToList();
                    List<int> intlst = new List<int>();
                    _mails.ForEach(x =>
                    {
                        intlst.Add(Convert.ToInt32(x));
                    });

                    lst.AddRange(GetUserInfo(intlst,null, 1));
                }
            }
            return lst;
        }

        private List<UserInfo> GetUserInfo(List<int> useridList, string[] loginidList, int accoutType)
        {
            List<UserInfo> lst = new List<UserInfo>();
            if (accoutType == 0)
            {
                List<BriefBatchUserReponseDto> batchUserReponselst = GetBriefBatchUserReponseDto(loginidList);
                if (batchUserReponselst != null)
                {
                    batchUserReponselst.ForEach(p =>
                    {
                        UserInfo userInfo = new UserInfo() { LoginID = p.LoginId, UserID = p.UserId };
                        lst.Add(userInfo);
                    });
                }
            }
            else
            {
                List<BatchUserReponseDto> batchUserReponselst = GetBatchUserReponseDto(useridList);
                if (batchUserReponselst != null)
                {
                    batchUserReponselst.ForEach(p =>
                    {
                        UserInfo userInfo = new UserInfo() {LoginID = p.LoginId, UserID = p.UserId};
                        lst.Add(userInfo);
                    });
                }
            }

            return lst;
        }
        /// <summary>
        /// 单个查询买手信息 通过sloginid
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static List<BriefBatchUserReponseDto> GetBriefBatchUserReponseDto(string[] loginIDList)
        {
            BriefBatchUserRequestDto request = new BriefBatchUserRequestDto() { LoginNameList = loginIDList };
            var response = Ymatou.ServiceCenter.ServiceClient.Execute<BriefBatchUserRequestDto, ResponseData<List<BriefBatchUserReponseDto>>>(request);
            if (response.Success)
            {
               return response.Result;
            }
            else
            {
                ApplicationLog.Info(string.Format("批量获取用户信息失败：ResponseCode:{0}", response.ResponseCode, response.LastErrorMessage));
                return null;
            }

        }

        /// <summary>
        /// 通过userid数组获取用户信息详情接口
        /// </summary>
        /// <param name="userIdList"></param>
        /// <returns></returns>
        public static List<BatchUserReponseDto> GetBatchUserReponseDto(List<int> userIdList)
        {
            if (userIdList == null || userIdList.Count == 0)
                return null;
            var request = new BatchUserRequestDto()
            {
                UserIdList = userIdList.ToArray()
            };
            var response = Ymatou.ServiceCenter.ServiceClient.Execute<BatchUserRequestDto, ResponseData<List<BatchUserReponseDto>>>(request);
            if (response.Success)
            {
                return response.Result;
            }
            else
            {
                ApplicationLog.Info(string.Format("获取用户信息失败：ResponseCode:{0},LastErrorMessage:{1},iuserid:{2}",
                    response.ResponseCode, response.LastErrorMessage, string.Join(",", request.UserIdList)));
                return null;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileName"></param>
        /// <param name="fileType">1图片，2文件</param>
        /// <returns></returns>
        public string UploadFile(byte[] fileData, string fileName, int fileType)
        {
            if (fileType == 1)
            {
                return UploadImage(fileData, fileName);
            }
            else
            {
                return UploadFile(fileData, fileName);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        string UploadFile(byte[] fileData, string fileName)
        {
            string url = "";
            try
            {
                var request = new Ymatou.File.Dto.Req.File.UploadFileWithByteReqModel()
                {
                    AppId = AppSettingHelper.GetAppSetting("AppId", "sellernotice.iapi.ymatou.com"),
                    FileBytes = fileData,
                    FileName = fileName
                };

                var file = Ymatou.File.FileClient.GetInstance();
                var response = file.UploadFileWithByte(request);
                if (response != null && response.Status == Ymatou.File.Constants.ResStatus.Success)
                {
                    url = response.Result.FileUrl;
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("Error调用保存数据接口：UploadFile({0})", fileName), ex);
            }
            return url;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        string UploadImage(byte[] fileData, string fileName)
        {
            string url = "";
            try
            {
                var request = new Ymatou.File.Dto.Req.Image.UploadPicWithByteReqModel()
                {
                    AppId = AppSettingHelper.GetAppSetting("AppId", "sellernotice.iapi.ymatou.com"),
                    FileBytes = fileData,
                    FileName = fileName,
                    PicType = "normal"
                };

                var file = Ymatou.File.ImageClient.GetInstance();
                var response = file.UploadPicWithByte(request);
                if (response != null && response.Status == Ymatou.File.Constants.ResStatus.Success)
                {
                    url = response.Result.PicUrl;
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("Error调用保存数据接口：UploadImage({0})", fileName), ex);
            }
            return url;
        }


        /// <summary>
        /// 删除通知附件
        /// </summary>
        /// <param name="detailModle"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool DeleteNoticeAttachment(List<long> noticeOptionIds, string noticeId)
        {
            return systemNoticeService.DeleteNoticeAttachment(noticeOptionIds, noticeId);
        }

        /// <summary>
        /// 保存通知消息
        /// </summary>
        /// <param name="detailModle"></param>
        /// <returns></returns>
        public bool SaveSystemNotice(SystemNoticeDetail detailModle, ref string msg)
        {
            if (detailModle.NoticeTarget == 1 && detailModle.TargetList != null && detailModle.TargetList.Count > 0)
            {
                //int uid = 0;
                //if (!int.TryParse(detailModle.TargetList[0], out uid))
                //{
                ApplicationLog.Info(string.Format("根据用户名获取用户ID，GetUserIDLstByLoginIds() 预通知对象列表：【{0}】", Newtonsoft.Json.JsonConvert.SerializeObject(detailModle.TargetList)));
                var lst = GetUserIDLstByLoginIds(detailModle.TargetList, 0);
                if (lst == null || lst.Count <= 0)
                {
                    msg = "，通知对象不存在";
                    return false;
                }

                var noList = detailModle.TargetList.Where(x => !lst.Select(k => k.LoginID).Contains(x)).ToList();

                if (noList != null && noList.Count > 0)
                {
                    msg = "，以下通知对象不存在：" + string.Join("，", noList);
                    ApplicationLog.Info(string.Format("根据用户名获取用户ID，GetUserIDLstByLoginIds() 不存在通知对象列表：【{0}】", Newtonsoft.Json.JsonConvert.SerializeObject(noList)));
                }
                detailModle.TargetList = (from p in lst
                                          select new UserInfo
                                          {
                                              LoginID = p.UserID.ToString()
                                          }).Select(x => x.LoginID).ToList();

                ApplicationLog.Info(string.Format("根据用户名获取用户ID，GetUserIDLstByLoginIds() 实际通知对象列表：【{0}】", Newtonsoft.Json.JsonConvert.SerializeObject(lst)));
                //}
            }
            if (detailModle.NoticeTarget == 2)
            {
                detailModle.NoticeTarget = 1;
            }
            return systemNoticeService.SaveSystemNotice(detailModle);
        }

        /// <summary>
        /// 获取通知消息详情
        /// </summary>
        /// <param name="noticeId"></param>
        /// <returns></returns>
        public SystemNoticeDetail GetSystemNoticeItem(string noticeId)
        {
            return systemNoticeService.GetSystemNoticeItem(noticeId);
        }

        /// <summary>
        /// 获取通知消息
        /// </summary>
        /// <param name="noticeTitle"></param>
        /// <param name="noticeType"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<SystemNotice> GetSystemNoticeList(string noticeTitle, NoticeTypeEnum noticeType, DateTime? beginTime, DateTime? endTime, int pageIndex, int pageSize, out int totalCount)
        {
            return systemNoticeService.GetSystemNoticeList(noticeTitle, noticeType, beginTime, endTime, pageIndex, pageSize, out totalCount);
        }

        #endregion

        #region 买手后台--通知中心

        /// <summary>
        /// 阅读通知保存
        /// </summary>
        /// <param name="sellerid"></param>
        /// <param name="noticeid"></param>
        /// <returns></returns>
        public bool SubmitReadNotice(int sellerid, string noticeid, string resource)
        {
            return systemNoticeService.SubmitReadNotice(sellerid, noticeid, resource);
        }

        /// <summary>
        /// 获取未读数
        /// </summary>
        /// <param name="state"></param>
        /// <param name="sellerid"></param>
        public int GetUnReadNoticeCount(string continent, int sellerid)
        {
            return systemNoticeService.GetUnReadNoticeCount(continent, sellerid);
        }

        /// <summary>
        /// 获取跑马灯
        /// </summary>
        /// <param name="state"></param>
        /// <param name="sellerid"></param>
        /// <returns></returns>
        public List<SystemNotice> GetMoveNoticeList(string continent, int sellerid)
        {
            List<SystemNotice> lst = new List<SystemNotice>();
            lst = systemNoticeService.GetMoveNoticeList(continent, sellerid);
            List<SystemNotice> retlist = new List<SystemNotice>();
            if (lst != null)
            {
                lst.ForEach(p =>
                {
                    SystemNotice item = new SystemNotice();
                    if (p.PublishTime != null &&
                        DateTime.Compare(p.PublishTime.Value.AddDays(p.NoticeRollingConfig), DateTime.Now) > 0)
                    {
                        item.PublishTime = p.PublishTime;
                        item.PublishTimeStr = p.PublishTime.ToString();
                        item.NoticeId = p.NoticeId;
                        item.NoticeTitle = p.NoticeTitle;
                        item.NoticeType = p.NoticeType;
                        item.NoticeTypeStr = ((NoticeTypeEnum)p.NoticeType).ToString();
                        retlist.Add(item);
                    }

                });
            }
            return retlist;

        }

        public List<SystemNotice> GetSellerAllNoticeList(string continent, int sellerid, int noticeType, int total)
        {
            List<SystemNotice> retlist = new List<SystemNotice>();
            retlist = systemNoticeService.GetSellerAllNoticeList(continent, sellerid, noticeType, total);
            if (retlist != null)
            {
                retlist.ForEach(p =>
                {
                    if (p.PublishTime != null)
                    {
                        p.NoticeNewFlag =
                            DateTime.Compare(p.PublishTime.Value.AddDays(3), DateTime.Now) > 0;
                    }
                    else
                    {
                        p.NoticeNewFlag = false;
                    }
                    p.NoticeTypeStr = ((NoticeTypeEnum)p.NoticeType).ToString();
                    p.PublishTimeStr = p.PublishTime.ToString();
                });
            }

            return retlist;
        }

        public List<SystemNoticeTypeEntity> GetSystemNoticeDetailList(int sellerid, string continent,
            NoticeTypeEnum noticeType,
            DateTime? beginTime, DateTime? endTime, int pageIndex, int pageSize, out int totalCount)
        {
            totalCount = 0;
            List<SystemNoticeTypeEntity> listSystemNoticeTypeEntity = new List<SystemNoticeTypeEntity>();

            if ((int)noticeType == 0)
            {
                List<SystemNoticeDetail> listNoticeDetail = systemNoticeService.GetSystemNoticeDetailList(sellerid,
                    continent, noticeType, beginTime, endTime,
                    pageIndex, pageSize, out totalCount);
                if (listNoticeDetail != null)
                {
                    listNoticeDetail.ForEach(p =>
                    {
                        p.NoticeTypeStr = ((NoticeTypeEnum)p.NoticeType).ToString();
                        p.AttachmentList =
                            systemNoticeService.GetSystemNoticeAttachmentList(new List<string>() { p.NoticeId });
                        if (p.AttachmentList != null && p.AttachmentList.Count(x => x.OptionType == 2) > 0)
                        {
                            p.HasAttachment = true;
                        }
                        p.PublishTimeStr = p.PublishTime.ToString();
                    });
                    SystemNoticeTypeEntity item = new SystemNoticeTypeEntity();
                    item.TotalCount = totalCount;
                    item.SystemNoticeDetailList = listNoticeDetail;
                    listSystemNoticeTypeEntity.Add(item);
                }

            }
            else
            {
                List<SystemNoticeDetail> listNoticeDetail = systemNoticeService.GetSystemNoticeDetailList(sellerid,
                    continent, noticeType, beginTime, endTime,
                    pageIndex, pageSize, out totalCount);
                if (listNoticeDetail != null)
                {
                    listNoticeDetail.ForEach(p =>
                    {
                        p.NoticeTypeStr = ((NoticeTypeEnum)p.NoticeType).ToString();
                        p.AttachmentList =
                            systemNoticeService.GetSystemNoticeAttachmentList(new List<string>() { p.NoticeId });
                        if (p.AttachmentList != null && p.AttachmentList.Count(x => x.OptionType == 2) > 0)
                        {
                            p.HasAttachment = true;
                        }
                        p.PublishTimeStr = p.PublishTime.ToString();
                    });
                    SystemNoticeTypeEntity item = new SystemNoticeTypeEntity();
                    item.TotalCount = totalCount;
                    item.SystemNoticeDetailList = listNoticeDetail;
                    listSystemNoticeTypeEntity.Add(item);
                }
            }



            return listSystemNoticeTypeEntity;
        }

        public List<NoticeTypeEntity> GetNoticeTypeList(int sellerid, string continent)
        {
            List<NoticeTypeEntity> listEnum = new List<NoticeTypeEntity>();
            foreach (NoticeTypeEnum itemEnum in Enum.GetValues(typeof(NoticeTypeEnum)))
            {
                if ((int)itemEnum == 0)
                    continue;
                NoticeTypeEntity noticeTypeItem = new NoticeTypeEntity();
                noticeTypeItem.Name = itemEnum.ToString();
                noticeTypeItem.Value = (int)itemEnum;
                noticeTypeItem.UnReadCount = systemNoticeService.GetNoticeTypeUnReadCount(sellerid, continent,
                    (int)itemEnum);
                listEnum.Add(noticeTypeItem);
            }
            return listEnum;
        }

        private string SellerAccountApiUrl
        {
            get
            {
                return ConfigurationManager.AppSettings["SellerAccountApiUrl"] != null ? ConfigurationManager.AppSettings["SellerAccountApiUrl"].ToString() : "http://selleraccount.iapi.ymatou.com";
            }
        }

        /// <summary>
        /// 通过买手id 获取买手所在的州
        /// </summary>
        /// <param name="sellerid"></param>
        /// <returns></returns>
        public string GetSellerInfo(int sellerid)
        {
            string retValue = "";
            var request = new GetSellerMainInfoRequest()
            {
                UserId = sellerid
            };
            var ret = Ymatou.API.Common.ApiClient.Execute<GetSellerMainInfoResponse>(request, SellerAccountApiUrl, 30000, null, true);
            if (ret != null)
            {
                if (ret.RetData != null && ret.RetData.SellerMainInfo != null)
                {
                    retValue = ret.RetData.SellerMainInfo.Continent;
                }
            }
            return retValue;
        }

        #endregion
    }
}
